import React, { PureComponent } from 'react'
import store from '../store'

// connect 本身返回一个高阶组件 高阶组件的本质就是函数
// mapStateToProps 本质是一个函数
export function connect(mapStateToProps, mapDispatchToProp) {
	return function enhanceHOC(WrappedComponent) {
		return class extends PureComponent {
            constructor(props) {
                super(props);
        
                this.state = {
                  storeState: mapStateToProps(store.getState())
                }
              }
        
              componentDidMount() {
                this.unsubscribe =store.subscribe(() => {
                  this.setState({
                    storeState: mapStateToProps(store.getState())
                  })    
                })
              }
        
              componentWillUnmount() {
                this.unsubscribe();
              }
			render() {
				// return <WrappedComponent counter={0} dispatch />不能写死 通过connect(mapStateToProps, mapDispatchToProp)
				return (
					<WrappedComponent
						{...this.props}
						{...mapStateToProps(store.getState())}
						{...mapDispatchToProp(store.dispatch)}
					/>
				)
			}
		}
	}
}
